package it.cst.entity.dao;


import it.cst.entity.User;

import java.util.List;


import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class UserDAOImpl implements UserDAO {

	@Autowired
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public void addUser(User user) {
		sessionFactory.getCurrentSession().save(user);
	}

	@SuppressWarnings("unchecked")
	public List<User> listUser() {
		return sessionFactory.getCurrentSession().createQuery("from User ORDER BY firstname,lastname")
				.list();
	}

	public void removeUser(Integer id) {
		User user = (User) sessionFactory.getCurrentSession().load(
				User.class, id);
		if (null != user) {
			sessionFactory.getCurrentSession().delete(user);
		}

	}


	public User getUser(String username) {
		Query q = sessionFactory.getCurrentSession().createQuery("from User WHERE username = ?");
		q.setString(0, username);
		return (User) q.uniqueResult();
	}

	@Override
	public void saveUser(User user) {
		sessionFactory.getCurrentSession().update(user);
	}

	@Override
	public User getUser(Integer userId) {
		Query q = sessionFactory.getCurrentSession().createQuery("from User WHERE id = ?");
		q.setInteger(0, userId);
		return (User) q.uniqueResult();
	}
}
